package org.bintrotter.stats;

import java.util.Date;

public class Stats {
	
	public class Report {
		
		public Report(	long inPieces,
						long inData,
						long outData,
						long inProtocol,
						long outProtocol,
						long timeFrameBegin,
						long timeFrameEnd	) {

			this.inPieces			= inPieces;
			this.inData				= inData;
			this.outData			= outData;
			this.inProtocol			= inProtocol;
			this.outProtocol		= outProtocol;
			this.timeFrameBegin		= timeFrameBegin;
			this.timeFrameEnd		= timeFrameEnd;			
		}
		
		public final long inPieces;
		public final long inData;
		public final long outData;
		public final long inProtocol;
		public final long outProtocol;
		public final long timeFrameBegin;
		public final long timeFrameEnd;
		
		private String xfer( long data ) {
		
			if(data<1000)
				return data + "bips";
			else
				return data/1000 + "." + (data/10 % 100) + "Kibps";
		}
		
		@Override
		public String toString() {
			
			long div = (timeFrameEnd - timeFrameBegin);
			
			if(div==0)
				return "[" + inData + "]" + "[" + outData + "]";
			
			float mult = 1000.0f/(float)(timeFrameEnd - timeFrameBegin);
			long ibps = (long) (mult * inData);
			long obps = (long) (mult * outData);
			return "download " + xfer(ibps) + ", upload " + xfer(obps); 
		}
	}
	 
	private long inPieces;
	private long inData;
	private long outData;
	private long inProtocol;
	private long outProtocol;
	private long timeFrameBegin;
	private long timeFrameEnd;
	private Report lastReport;
	
	public Stats() {
		
		reset();
	}
	
	public void reset() {
		inPieces =
		inData =
		outData =
		inProtocol =
		outProtocol = 0;
		timeFrameEnd = timeFrameBegin = (new Date()).getTime();
	}
	
	public Report newReport() {
		
		timeFrameEnd = (new Date()).getTime();

		lastReport = (new Report(
						inPieces,
						inData,
						outData,
						inProtocol,
						outProtocol,
						timeFrameBegin,
						timeFrameEnd));
		
		reset();
		
		return lastReport;
	}
	
	public Report lastReport() {
		
		return lastReport;
	}
	
	public void overheadOut(int size) {
		
		outProtocol += size;
	}
	
	public void overheadIn(int size) {
		
		inProtocol += size;
	}
	
	public void dataOut(int size) {
		
		outData += size;
	}
	
	public void dataIn(int size) {
		
		inData += size;
	}
	
	public void gotPiece(int num) {
		
		inPieces += num;
	}
}


